package com.investmenttechnologyservices.services;

import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.investmenttechnologyservices.rest.RestServlet;

public class UploadService {
	
    private static final Logger log = Logger.getLogger(UploadService.class.getName());
	
	public void upload(HttpServletRequest req, HttpServletResponse res) throws ServletException {
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iterator = upload.getItemIterator(req);
			if (iterator.hasNext()) { // take only the first one
				FileItemStream item = iterator.next();
//				InputStream stream = item.openStream();
	
				if (item.isFormField()) {
					throw new ServletException(RestServlet.class.getName() + "does not support forms");
				} else {
					log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
//					ObjectMapper m = new ObjectMapper();
//					JsonNode node = m.readTree(stream);
				}
			}
		} catch (Exception ex) {
			throw new ServletException("Error in upload " + ex.getLocalizedMessage());
		}
	}
}
